﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using HuaCheng.DataAccess;
using HuaCheng.Model;
using HuaCheng.Views;

namespace HuaCheng.Controller
{
    public class TxtControl
    {
        /// <summary>
        /// 将本地日志列表写入txt
        /// </summary>
        /// <param name="localLog"></param>
        public static void WriteLocalLogToTxt(LocalLog localLog)
        {
            //查询本地日志文件地址
            string localLogArr = DicHelper.RetrieveLocalLogPath();
            //创建txt文件的写入路径
            string saveFileName = localLogArr + System.DateTime.Now.ToShortDateString().Replace("/", "") + "Local.log";
            StringBuilder builder = new StringBuilder();
            FileStream fs;
            if (!File.Exists(saveFileName))
            {
                fs = new FileStream(saveFileName, FileMode.OpenOrCreate,FileAccess.Write,FileShare.ReadWrite);
            }
            else
            {
                fs = new FileStream(saveFileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
            }
            StreamWriter sw = new StreamWriter(fs, Encoding.Default);
            builder.AppendLine(localLog.TestATime.ToShortDateString() + "\t" + localLog.TestATime.ToShortTimeString() + "\t" + localLog.Record + "\t" + localLog.LocalEvent + "\t" + IndexPage.username);
            sw.Write(builder);
            sw.Close();
            fs.Close();
        }
        /// <summary>
        /// 从txt文件中读取本地日志列表
        /// </summary>
        public static List<LocalLog> ReadListFromTxt()
        {
            List<LocalLog> localLogList = new List<LocalLog>();
            //查询本地日志文件地址
            string localLogArr = DicHelper.RetrieveLocalLogPath();
            //创建txt文件的具体路径
            string openFileName = localLogArr + System.DateTime.Now.ToShortDateString().Replace("/", "") + "Local.log";
            FileStream fs = new FileStream(openFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            //实例化StreamReader
            StreamReader sr = new StreamReader(fs, Encoding.Default);
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                LocalLog localLog = new LocalLog();
                string[] arrLocalLog = line.Split(new char[] { '\t' });
                localLog.TestATime = Convert.ToDateTime(arrLocalLog[0] + " " + arrLocalLog[1]);
                localLog.Record = arrLocalLog[2];
                localLog.LocalEvent = arrLocalLog[3];
                localLogList.Add(localLog);
            }
            return localLogList;
        }
    }
}
